<?php
include './include/common.inc.php';

if($action=="check"){
    if($fun && $val){
        
        if($fun=='ask1' || $fun=='ask2' || $fun=='ans1' || $fun=='ans2'){
            $fun='askans';
        }
        
        $fun='chk'.$fun;
        if(function_exists($fun)){
            
            echo $fun($val);
            exit;
        }else{
            echo "<b>系统错误:检测函数未定义，请联系管理员</b>";
            exit;
        }
    }
}else{
    if($submit){
        
        if(chkusername($username)=='√' && chkpw($pw)=='√' && chkemail($email)=='√' && chkaskans($ask1)=='√' && chkaskans($ask2)=='√' && chkaskans($ans1)=='√' && chkaskans($ans2)=='√' ){
            $q=$db->fetch_first("select name from member where name='{$username}'");
            if($q){
                if($from=='ajax'){
                    echo '用户名已存在，请重新构思用户名！';
                    exit;
                }
            }
            $pw=md5($_POST['pw']);
            $olip=$_SERVER['REMOTE_ADDR'];
            $nowtime=time();
            $db->query("insert into member (name,pw,olip,regtime,ask1,ans1,ask2,ans2,email) values ('{$username}','{$pw}','{$olip}',{$nowtime},'{$ask1}','{$ans1}','{$ask2}','{$ans2}','{$email}')");
            if($from=='ajax'){
                echo 'ok';
            }                       
        }else{
            if($from=='ajax'){
                echo '提交的信息含有非法参数，请按照正常步骤一一填写！';
            }
        }
        
        
    }else{
        $tpl->assign("title","新用户注册");
        $tpl->display("register.html");
    }
}
function chkusername($val){
    global $db;
    $msg="√";
    if(!isset($val[5]) || isset($val[15])){
        $msg="<b>用户名长度过短或太长，请6-15个字符</b>";
        return $msg;
    }
    if(preg_match("/[^0-9a-zA-Z_]+/", $val)){
        $msg="<b>不得包含数字，字母，下划线以外的字符!</b>";
        return $msg;
    }
    $q=$db->fetch_first("select name from member where name='{$val}'");
    if($q){
        $msg="<b>用户名已存在!</b>";
        return $msg;
    }
    return $msg;
}
function chkpw($val){
    $msg="√";
    if(!isset($val[5]) || isset($val[15])){
        $msg="<b>过短或太长，请6-15个字符</b>";
        return $msg;
    }
    return $msg;
}
function chkemail($val){
    $msg="√";
    if(!filter_var($val,FILTER_VALIDATE_EMAIL)){
        $msg="<b>E-MAIL地址不合法</b>";
        return $msg;
    }            
    return $msg;
}
function chkaskans($val){
    $msg="√";
    if(trim($val)==""){
        $msg="<b>不能为空</b>";
        return $msg;
    }
    return $msg;
}